package com.xinongbest.mall.filter;

import com.xinongbest.mall.common.Constant;
import com.xinongbest.mall.model.pojo.User;
import com.xinongbest.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.io.PrintWriter;

public class AdminFilter implements Filter {

    @Autowired
    UserService userService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        User user = (User) request.getSession().getAttribute(Constant.IMOOC_MALL_USER);
        if (user == null) {
            PrintWriter writer = new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            writer.write("{\"status\":\"10007\",\"msg\":\"NEED_LOGIN\",\"data\": null}");
            writer.flush();
            writer.close();
            return;
        }
        if (userService.checkAdminRole(user)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            PrintWriter writer = new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            writer.write("{\"status\":\"10009\",\"msg\":\"NEED_ADMIN\",\"data\": null}");
            writer.flush();
            writer.close();
        }
    }
}
